<template>
    <div>
        <el-row style="margin: 5px 20px 0; height:40px; display:flex; align-items:center;">
            <span>蜡块列表</span>
        </el-row>
        <el-row
            style="max-width: max-content; height: 120px;
        padding: 0 20px; overflow: auto"
            type="flex"
            align="middle"
        >
            <img
                v-for="(wax, index) in waxList"
                style="width: 100px; height: 100px; margin-right: 15px"
                :key="index"
                :src="wax"
                @click="imageDialogOpen(wax)"
            >
        </el-row>

        <el-form
            ref="projectAddFilter"
            :model="projectAddFilter"
            label-width="80px"
            :rules="projectAddRule"
        >
            <el-row style="height:60px; display:flex; align-items:center;">
                <el-col :span="4">
                    <el-form-item
                        label="病理编号"
                        prop="pathID"
                    >
                        <span style="color: red; margin: 0 8px">{{data.pathologyId}}</span>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item
                        label="蜡块"
                        prop="wax"
                    >
                        <el-input
                            v-model.trim="projectAddFilter.wax"
                            placeholder="请输入蜡块"
                            class="filter-input"
                            size="mini"
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="3">
                    <el-form-item label="类型">
                        <el-select
                            v-model="projectAddFilter.type"
                            placeholder="请选择加做项目"
                            @change="projectTypeChange"
                            size="mini"
                            class="filter-picker"
                        >
                            <el-option
                                v-for="(item, index) in projectTypeDict"
                                :key="index"
                                :label="item.name"
                                :value="item.id"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <el-row
                        type="flex"
                        align="middle"
                        :gutter="10"
                    >
                        <el-col :span="18">
                            <el-form-item label="医嘱备注">
                                <el-input
                                    v-model="projectAddFilter.remark"
                                    placeholder="请输入医嘱备注"
                                    class="filter-input"
                                    size="mini"
                                    maxlength="200"
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button
                                size="mini"
                                type="primary"
                                @click="addProject"
                                :disabled="isFinished"
                            >
                                添加
                            </el-button>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
        </el-form>
        <hr>
        <el-row>
            <base-table
                ref="techAdviceTable"
                v-loading="!techAdviceTable.isLoaded"
                :data="adviceSliceData"
                :header="techAdviceTable.header"
                :operation="techAdviceTable.operation"
                :pageInfo="techAdviceTable.pageInfo"
                :selected="techAdviceTable.selected"
                :cellStyleFunc="cellClass"
                :buttonVisibleFunc="tableButtonVisibleFunc"
                :pageSizes="[5, 10, 15]"
                @handleClick="adviceTableButtonClick"
                @pageJumpTo="adviceTablePageJumpTo"
                @sizeChange="adviceTableSizeChange"
            >
            </base-table>
        </el-row>
        <el-dialog
            append-to-body
            title="病理切片"
            :visible.sync="imageDialog"
            width="60%"
            center
        >
            <el-row
                style="margin-top: 10px"
                type="flex"
                justify="center"
            >
                <img
                    style="max-height: 800px; max-width: 800px"
                    :src="waxPreviewSrc"
                >
            </el-row>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    size="mini"
                    @click="imageDialog = false"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import _ from 'lodash';

// 加做流程
const doctorAdviceFlowBase = [
    {
        level: -1,
        label: '已删除',
    },
    {
        level: 1,
        label: '待批准',
    },
    {
        level: 2,
        label: '已批准',
    },
    {
        level: 3,
        label: '待加做',
    },
    {
        level: 4,
        label: '已加做',
    },
];

export default {
    name: 'DiagnosisTechAdvice',
    props: {
        data: Object,
        permission: {
            type: Number,
            default: 0, // 0-只能查看，1-只能新增，2-既能新增也能审核、删除
        },
    },
    components: {
        BaseTable,
    },
    data() {
        const checkAddWax = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请填写蜡块');
            } else {
                callback();
            }
        };

        return {
            doctorAdviceFlow: doctorAdviceFlowBase,
            imageServiceURL: process.env.ImageServiceURL, // 图片服务器地址
            imageDialog: false, // 蜡块预览模态框
            waxList: [],
            waxImageSrc: '',
            projectAddFilter: {
                typeName: '',
                wax: '',
                pathID: '',
                type: '',
                remark: '',
            },
            projectTypeList: [], // 加做类型列表
            specialProjectSelection: [],

            projectAddRule: {
                wax: [
                    {
                        required: true,
                        message: ' ',
                        validator: checkAddWax,
                        trigger: 'blur',
                    },
                ],
            },
            techAdviceTable: {
                isLoaded: false,
                selected: false,
                data: [],
                header: [
                    {
                        prop: 'typeName',
                        label: '检查类型',
                    },
                    {
                        prop: 'pathologyID',
                        label: '病理编号',
                    },
                    {
                        prop: 'statusName',
                        label: '状态',
                    },
                    {
                        prop: 'wax',
                        label: '蜡块',
                    },
                    {
                        prop: 'reagentName',
                        label: '项目',
                    },
                    {
                        prop: 'applyDrName',
                        label: '申请医生',
                    },
                    {
                        prop: 'applyDate',
                        label: '申请时间',
                    },
                    {
                        prop: 'auditDrName',
                        label: '审核医生',
                    },
                    {
                        prop: 'auditDate',
                        label: '审核时间',
                    },
                    {
                        prop: 'remark',
                        label: '备注',
                    },
                ],
                operation: [
                    {
                        label: '审核',
                        functionKey: 'singleAudit',
                    },
                    // 暂时不使用 “删除” 功能，所有操作均为“移除”
                    // {
                    //   label: '删除',
                    //   color: 'red',
                    //   functionKey: 'singleDelete',
                    // },
                    // 暂时不使用 “删除” 功能，并将“移除”功能重命名为 删除
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'singleRemove',
                    },
                ],
                pageInfo: {
                    page: 1,
                    size: 10,
                    total: 0,
                },
            },
            isFinished: this.data.currentLevel === 6 ? true : false,
        };
    },
    mounted() {
        this.waxListRequest();
        this.extraProjectRequest();
        this.projectTypeRequest();
    },
    methods: {
        // 打开蜡块预览模态框
        imageDialogOpen(wax) {
            this.waxImageSrc = wax;
            this.imageDialog = true;
        },
        // 获取蜡块图
        waxListRequest() {
            this.waxList = [];
            if (this.data.biopsyList) {
                this.data.biopsyList.forEach((item) => {
                    this.waxList.push(this.imageServiceURL + item.labelUrl);
                });
            }
        },
        // 获取已加做项目列表
        async extraProjectRequest() {
            try {
                await this.$axios({
                    url: '/PROXY-Remote/diagnosis/extra-project/search',
                    method: 'POST',
                    params: {
                        diagnosisId: this.data.id,
                        page: 0,
                        size: 999,
                    },
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    this.techAdviceTable.data = [];
                    // this.techAdviceTable.data = _.clone(res.data.data);
                    res.data.data.forEach((project) => {
                        if (project.doctorType === 4) {
                            const item = {};
                            item.id = project.id;
                            item.typeName = '技术医嘱';
                            item.pathologyID = this.data.pathologyId || '-';
                            item.wax = project.wax || '-';
                            item.reagentName = project.doctorAdviceName || '-';
                            item.applyDrName = project.applyDoctorName || '-';
                            item.applyDate = project.createTime || '-';
                            item.auditDrName = project.reviewDoctorName || '-';
                            item.auditDate = project.reviewTime || '-';
                            item.remark = project.remark || '-';
                            item.statusName = project.currLevel
                                ? this.adviceLevel2Label(project.currLevel)
                                      .label
                                : '-';
                            item.doctorAdviceId = project.doctorAdviceId;
                            item.currLevel = project.currLevel;
                            this.techAdviceTable.data.push(item);
                        }
                    });
                    this.techAdviceTable.pageInfo.total =
                        this.techAdviceTable.data.length;
                    this.techAdviceTable.isLoaded = true;
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        // 获取加做项目类型列表
        async projectTypeRequest() {
            this.projectAddFilter.type = ''; // 清空原有数据
            try {
                // 请求单项
                await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/doctor-advices',
                    params: {
                        page: 0,
                        size: 999,
                        type: 4,
                    },
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    this.projectTypeList = [];
                    this.projectTypeList = _.clone(res.data.data);
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        projectTypeChange() {
            console.log('projectTypeChange');
        },
        reagentChange() {
            console.log('reagentChange');
        },
        groupChange() {
            console.log('groupChange');
        },
        // 添加单项
        async addSingleItem(adviceId) {
            try {
                const { state } = this.$store;
                const { user } = state;
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/diagnosis/extra-project',
                    params: {
                        ids: adviceId,
                    },
                    data: {
                        diagonisisId: this.data.id,
                        doctorId: user.id,
                        wax: this.projectAddFilter.wax,
                        remark: this.projectAddFilter.remark,
                    },
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    this.$message.success('添加成功！');
                    this.extraProjectRequest(); // 刷新列表
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        // 单个添加
        addProject() {
            this.$refs.projectAddFilter.validate((valid) => {
                if (!valid) {
                    return false;
                }
                if (this.projectAddFilter.type === '') {
                    this.$message.warning('请在类型里选择需要添加的项目');
                    return false;
                }
                if (this.techAdviceTable.data !== []) {
                    // 判断是否存在重复
                    for (let i = 0; i < this.techAdviceTable.data.length; i++) {
                        const item = this.techAdviceTable.data[i];
                        // 单项id 与 针对切片 与 针对蜡块一致
                        if (
                            item.doctorAdviceId ===
                                this.projectAddFilter.type &&
                            item.wax === this.projectAddFilter.wax &&
                            item.currLevel > 0
                        ) {
                            this.$message.warning('项目已存在，请勿重复添加');
                            return false;
                        }
                    }
                }
                this.addSingleItem(this.projectAddFilter.type);
                this.projectAddFilter = {
                    wax: '',
                    type: '',
                    remark: '',
                };

                return true;
            });
        },
        // 移除单项
        async singleRemove(row) {
            try {
                await this.$axios({
                    method: 'DELETE',
                    url: `/PROXY-Remote/diagnosis/extra-project/${row.id}`,
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    this.extraProjectRequest();
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        // 删除单项
        // async singleDelete(row) {
        //   try {
        //     await this.$axios({
        //       method: 'POST',
        //       url: '/PROXY-Remote/diagnosis/extra-project/checkout',
        //       params: {
        //         id: row.id,
        //         type: 2,
        //       },
        //     }).then((res, err) => {
        //       if (res.data.code !== 200) {
        //         throw new Error(err);
        //       }
        //       this.extraProjectRequest();
        //     });
        //   } catch (e) {
        //     throw new Error(e);
        //   }
        // },
        // 审核单项
        async singleAudit(row) {
            try {
                await this.$axios({
                    method: 'POST',
                    url: '/PROXY-Remote/diagnosis/extra-project/checkout',
                    params: {
                        id: row.id,
                        type: 1,
                    },
                }).then((res, err) => {
                    if (res.data.code !== 200) {
                        throw new Error(err);
                    }
                    this.extraProjectRequest();
                });
            } catch (e) {
                throw new Error(e);
            }
        },
        // 表格单项ui设置
        cellClass({ row, column }) {
            const baseStyle = {
                padding: '3px 0',
                'border-right': '1px solid #ffffff',
                'font-size': '14px',
            };

            if (column.label === '状态') {
                switch (row.statusName) {
                    case '已删除':
                        baseStyle.color = '#ff0000';
                        break;
                    case '待批准':
                        baseStyle.color = '#000000';
                        break;
                    case '已批准':
                        baseStyle.color = '#00BE8B';
                        break;
                    case '待加做':
                        baseStyle.color = '#00b0f0';
                        break;
                    default:
                        baseStyle.color = '#000000';
                        break;
                }
            }
            return baseStyle;
        },
        adviceLevel2Label(adviceLevel) {
            return this.doctorAdviceFlow.find((t) => t.level === adviceLevel);
        },
        adviceTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        adviceTablePageJumpTo(val) {
            this.techAdviceTable.pageInfo.page = val;
        },
        adviceTableSizeChange(val) {
            this.techAdviceTable.pageInfo.size = val;
        },
        tableButtonVisibleFunc(functionKey, row) {
            switch (functionKey) {
                case 'singleRemove':
                    return (
                        (this.permission === 1 || this.permission === 2) &&
                        row.currLevel === 1
                    );
                // case 'singleDelete':
                //   return this.permission === 2 && row.currLevel === 1;
                case 'singleAudit':
                    return this.permission === 2 && row.currLevel === 1;
                default:
                    return true;
            }
        },
    },
    computed: {
        projectTypeDict() {
            return this.projectTypeList;
        },
        waxPreviewSrc() {
            return this.waxImageSrc;
        },
        adviceSliceData() {
            const { pageInfo } = this.techAdviceTable;
            return this.techAdviceTable.data.slice(
                (pageInfo.page - 1) * pageInfo.size,
                pageInfo.page * pageInfo.size
            );
        },
    },
};
</script>

<style scoped>
.filter-input {
    width: 100%;
    max-width: 210px;
}
.filter-picker {
    width: 100%;
    max-width: 210px;
}
</style>
